import { observable, action, flow, makeObservable } from "mobx"
import axios from 'axios'
import UserStore from "./UserStore"

export default class UserListStore {
  constructor(users) {
    // 已有数据时的初始化
    this.users = users ? users.map(user => new UserStore(user)) : []

    // 必须放到成员声明后面
    makeObservable(this, {
      users: observable,
      addUser: action.bound,
      delUser: action.bound,
      loadData: flow.bound
    })

    // 如果服务端使用异步Mobx预取数据就放到这里执行
    // 如果客户端使用异步Mobx取数据就放到组件useEffect里面调用
    this.users.length === 0 && this.loadData()
  }
  addUser(user) {
    this.users.push(new UserStore(user))
  }
  delUser() {
    this.users.pop()
  }
  // flow 替代 async/await 写法进行异步请求
  *loadData() {
    let response = yield axios.get("http://localhost:3001/users")
    response.data.map(user => {
      this.users.push(new UserStore(user))
    })
  }
}